package com.bosch.in.rtp1.ept.action;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.MappingDispatchAction;

import com.bosch.in.rtp1.ept.action.form.LoginForm;
import com.bosch.in.rtp1.ept.manager.AuthenticationManager;
import com.bosch.in.rtp1.ept.util.ManagerFactory;

/**
 * Class is used to display login form and authenticate provided password from user.
 * Only valid password validation, user is able to access configuration pages.
 * @author TPR1HC
 *
 */
public class LoginAction extends MappingDispatchAction{
	
	private static final Logger LOGGER = Logger.getLogger(LoginAction.class);
	
	/**
	 * flag indicates if user is authenticated or not.
	 */
	public static final String LOGON = "logon";
	
	/**
	 * This method just map parameter into ActionForm automatically. And 
	 * then forward to login page.
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws SQLException 
	 */
	public ActionForward display(ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response) throws SQLException 
			 {
		LOGGER.debug("Begin display");
		LOGGER.debug("End display");
		
        return mapping.findForward("success");
	}
	
	/**
	 * Validate password, if password is correct it will redirect user to original 
	 * link user want to access. Otherwise, user must provide password again.
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws SQLException 
	 * @throws IOException 
	 */
	public ActionForward login(ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response) throws SQLException, IOException 
			 {
		LOGGER.debug("Begin login");
		LoginForm loginForm = (LoginForm) form;
		
		// validate password
		// create AuthenticationManager manager instance
		AuthenticationManager authenticationManager = ManagerFactory.getInstance().getAuthenticationManager();
		loginForm.setError(!authenticationManager.validatePassword(loginForm.getPassword()));
		
		if (!loginForm.isError()) {
			request.getSession(true).setAttribute(LOGON, true);
			ActionForward success = new ActionForward(loginForm.getOriginalUrl(), true);
			return success;
		} else {
			loginForm.setError(true);
			
			LOGGER.debug("End login");
			
			return mapping.findForward("fail");
		}
	}
}
